<?php
/**
* @file $Id: InputFinalGrades.php 552 2007-06-04 05:14:31Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

include $staticpath.'ProgramFunctions/_makeLetterGrade.fnc.php';
DrawHeader(ProgramTitle());

$course_period_id = UserCoursePeriod();
$course_id = DBGet(DBQuery("SELECT c.GRAD_SUBJECT_ID,cp.COURSE_ID,cp.TITLE,c.TITLE AS COURSE_TITLE,c.SHORT_NAME AS COURSE_NUM,cw.CREDITS,cw.GPA_MULTIPLIER,cp.DOES_GRADES,cp.GRADE_SCALE_ID,cp.DOES_GPA as AFFECTS_GPA FROM COURSE_PERIODS cp,COURSES c,COURSE_WEIGHTS cw WHERE cw.COURSE_ID=cp.COURSE_ID AND cw.COURSE_WEIGHT=cp.COURSE_WEIGHT AND c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_PERIOD_ID='".UserCoursePeriod()."'"));
if($course_id[1]['DOES_GRADES']!='Y')
	DrawHeader(ErrorMessage(array(_('You cannot enter grades for this period.')),'fatal'),' &nbsp;');
$grade_scale_id = $course_id[1]['GRADE_SCALE_ID'];
$cp_title = $course_id[1]['TITLE'];
$course_title = $course_id[1]['COURSE_TITLE'];
$course_num = $course_id[1]['COURSE_NUM'];
$credits = $course_id[1]['CREDITS'];
$gpa_multiplier = $course_id[1]['GPA_MULTIPLIER'];
$affects_gpa = $course_id[1]['AFFECTS_GPA'];
$grad_subject = $course_id[1]['GRAD_SUBJECT_ID'];
$course_id = $course_id[1]['COURSE_ID'];


$time = strtotime(DBDate('postgres'));
// IF THE UserMP HAS BEEN CHANGED, THE CURRENT MP WILL NOT WORK
if(!$_REQUEST['mp'] && GetMP(UserMP(),'POST_START_DATE') && ($time >= strtotime(GetMP(UserMP(),'POST_START_DATE')) && $time <= strtotime(GetMP(UserMP(),'POST_END_DATE'))))
	$_REQUEST['mp'] = UserMP();
elseif(strpos(GetAllMP('QTR',UserMP()),"'".str_replace('E','',$_REQUEST['mp'])."'")===false && strpos(GetChildrenMP('PRO',UserMP()),"'".$_REQUEST['mp']."'")===false  && ($time >= strtotime(GetMP(UserMP(),'POST_START_DATE')) && $time <= strtotime(GetMP(UserMP(),'POST_END_DATE'))))
	$_REQUEST['mp'] = UserMP();

if(!$_REQUEST['mp'] && GetMP(GetParentMP('SEM',UserMP()),'POST_START_DATE') && ($time >= strtotime(GetMP(GetParentMP('SEM',UserMP()),'POST_START_DATE')) && $time <= strtotime(GetMP(GetParentMP('SEM',UserMP()),'POST_END_DATE'))))
	$_REQUEST['mp'] = GetParentMP('SEM',UserMP());	

if(!$_REQUEST['mp'] && GetMP(GetParentMP('FY',GetParentMP('SEM',UserMP())),'POST_START_DATE') && ($time >= strtotime(GetMP(GetParentMP('FY',GetParentMP('SEM',UserMP())),'POST_START_DATE')) && $time <= strtotime(GetMP(GetParentMP('FY',GetParentMP('SEM',UserMP())),'POST_END_DATE'))))
	$_REQUEST['mp'] = GetParentMP('FY',GetParentMP('SEM',UserMP()));	

$pro = GetChildrenMP('PRO',UserMP());
$pros = explode(',',str_replace("'",'',$pro));
$pro_grading = false;

foreach($pros as $pro)
{
	if(GetMP($pro,'POST_START_DATE') && ($time >= strtotime(GetMP($pro,'POST_START_DATE')) && $time <= strtotime(GetMP($pro,'POST_END_DATE'))))
	{
		if(!$_REQUEST['mp'])
			$_REQUEST['mp'] = $pro;

		$pro_grading = true;
	}
}


if($_REQUEST['mp'])
	$current_RET = DBGet(DBQuery("SELECT g.STUDENT_ID,g.REPORT_CARD_GRADE_ID,g.REPORT_CARD_COMMENT_ID,g.COMMENT,g.PERCENT FROM STUDENT_REPORT_CARD_GRADES g,COURSE_PERIODS cp WHERE cp.COURSE_PERIOD_ID=g.COURSE_PERIOD_ID AND cp.COURSE_PERIOD_ID='$course_period_id' AND g.MARKING_PERIOD_ID='".$_REQUEST['mp']."'"),array(),array('STUDENT_ID'));
$grades_RET = DBGet(DBQuery("SELECT ID,TITLE,GPA_VALUE,DEFAULT_BREAKOFF,CREDITS FROM REPORT_CARD_GRADES WHERE SCALE_ID='".$grade_scale_id."' AND SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."' ORDER BY SORT_ORDER"),array(),array('TITLE'));
$comments_RET = DBGet(DBQuery("SELECT ID,TITLE FROM REPORT_CARD_COMMENTS WHERE SCHOOL_ID='".UserSchool()."' AND SYEAR='".UserSyear()."' ORDER BY TITLE"));
$config_RET = DBGet(DBQuery("SELECT TITLE,VALUE FROM PROGRAM_USER_CONFIG WHERE USERNAME='".User('USERNAME')."' AND PROGRAM='Gradebook'"),array(),array('TITLE'));
if(count($config_RET))
{
	foreach($config_RET as $title=>$value)
		$programconfig[$title] = $value[1]['VALUE'];
}

if(!$_FOCUS['_makeLetterGrade']['grades'])
	$_FOCUS['_makeLetterGrade']['grades'] = DBGet(DBQuery("SELECT TITLE,ID,DEFAULT_BREAKOFF FROM REPORT_CARD_GRADES WHERE SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."' AND SCALE_ID='".$grade_scale_id."' ORDER BY SORT_ORDER"));
//$grades = array('A+','A','A-','B+','B','B-','C+','C','C-','D+','D','D-','F');

$custom = false;
foreach($_FOCUS['_makeLetterGrade']['grades'] as $grade)
{
	if($programconfig[$course_period_id.'-'.$grade['ID']])
	{
		$custom = true;
		break;
	}
}

if(!$custom)
{
	foreach($_FOCUS['_makeLetterGrade']['grades'] as $grade)
		$programconfig[$course_period_id.'-'.$grade['ID']] = $grade['DEFAULT_BREAKOFF'];
}


if($_REQUEST['modfunc']=='gradebook')
{
	if(Prompt(_('Confirm Use Gradebook Grades'),_('Are you sure you want to use your gradebook grades to calculate final grades for ').GetMP($_REQUEST['mp']).'?'))
	{
		if(GetMP($_REQUEST['mp'],'TABLE')=='SCHOOL_SEMESTERS' && SystemPreferences('REPORT_CARD')!='grade')
		{
			// THIS SHOULDN'T JOIN ON REPORT_CARD_GRADES ... USE THIS QUERY IF THE CONFIG IS AVERAGE GPA VALUE -- THIS SECTION IS ACTUALLY AVERAGE PERCENT
			$points_RET = DBGet(DBQuery("SELECT srg.STUDENT_ID,rg.GPA_VALUE,srg.MARKING_PERIOD_ID,srg.PERCENT FROM STUDENT_REPORT_CARD_GRADES srg,REPORT_CARD_GRADES rg WHERE srg.COURSE_PERIOD_ID='".$course_period_id."' AND MARKING_PERIOD_ID IN (".GetAllMP('SEM',$_REQUEST['mp']).",'E".GetParentMP('SEM',UserMP())."') AND srg.REPORT_CARD_GRADE_ID=rg.ID"),array(),array('STUDENT_ID'));
			foreach($points_RET as $student_id=>$grades)
			{
				$total = 0;
				$count = count($grades);
				foreach($grades as $grade)
				{
					if(GetMP($grade['MARKING_PERIOD_ID'],'TABLE')=='SCHOOL_QUARTERS')
						$total += $grade['PERCENT'];
					else
						$count -= 1;
				}
				$total = $percent = $total / $count;
				$total /= 100;

				if($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['CREDITS']!='Y')
					$carries_credits = '';
				else
					$carries_credits = 'Y';

				if($current_RET[$student_id])
					$sql = "UPDATE STUDENT_REPORT_CARD_GRADES SET GRADE_TITLE='"._makeLetterGrade($total,UserCoursePeriod())."',REPORT_CARD_GRADE_ID='".$grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['ID']."',PERCENT='".$percent."',GPA_POINTS='".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits)."',WEIGHTED_GPA_POINTS='".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits*$gpa_multiplier)."',CREDITS='".$credits."',CARRIES_CREDITS='".$carries_credits."' WHERE STUDENT_ID='".$student_id."' AND COURSE_PERIOD_ID='".$course_period_id."' AND MARKING_PERIOD_ID='".$_REQUEST['mp']."'";
				else
					$sql = "INSERT INTO STUDENT_REPORT_CARD_GRADES (ID,SYEAR,SCHOOL_ID,STUDENT_ID,COURSE_PERIOD_ID,MARKING_PERIOD_ID,REPORT_CARD_GRADE_ID,COURSE_TITLE,TEACHER,GRAD_SUBJECT_ID,LOCATION_TITLE,PERCENT,CREDITS,CARRIES_CREDITS,COURSE_NUM,AFFECTS_GPA,GPA_POINTS,WEIGHTED_GPA_POINTS,GRADE_TITLE,GRADE_SCALE_ID)
							values(".db_seq_nextval('STUDENT_REPORT_CARD_GRADES_SEQ').",'".UserSyear()."','".UserSchool()."','".$student_id."','".$course_period_id."','".$_REQUEST['mp']."','".$grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['ID']."',
									'".$course_title."','".GetTeacher(User('STAFF_ID'))."','".$grad_subject."','".str_replace("'","''",GetSchool(UserSchool()))."','".$percent."','".$credits."','".$carries_credits."','".$course_num."','".$affects_gpa."','".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits)."','".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits*$gpa_multiplier)."','"._makeLetterGrade($total,UserCoursePeriod())."','".$grade_scale_id."')";
				DBQuery($sql);
			}				
		}
		elseif(true || GetMP($_REQUEST['mp'],'TABLE')=='SCHOOL_QUARTERS' || GetMP($_REQUEST['mp'],'TABLE')=='SCHOOL_PROGRESS_PERIODS')
		{
			if($programconfig['WEIGHT']=='Y')
				$points_RET = DBGet(DBQuery("SELECT gt.ASSIGNMENT_TYPE_ID,gg.STUDENT_ID,(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'gg.POINTS')).") * gt.FINAL_GRADE_PERCENT) AS PARTIAL_PERCENT_TOP, (sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).")) AS PARTIAL_PERCENT_BOTTOM 
												FROM GRADEBOOK_GRADES gg, GRADEBOOK_ASSIGNMENTS ga, GRADEBOOK_ASSIGNMENT_TYPES gt, SCHEDULE s 
												WHERE s.COURSE_PERIOD_ID=gg.COURSE_PERIOD_ID AND ('".DBDate()."' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL AND '".DBDate()."'>=s.START_DATE)) 
												AND gt.ASSIGNMENT_TYPE_ID=ga.ASSIGNMENT_TYPE_ID AND ga.ASSIGNMENT_ID=gg.ASSIGNMENT_ID AND ga.MARKING_PERIOD_ID IN (".GetAllMP('QTR',UserMP()).") AND gg.COURSE_PERIOD_ID='$course_period_id' AND gt.COURSE_ID='$course_id' 
												AND (ga.COURSE_PERIOD_ID='$course_period_id' OR ga.COURSE_ID='$course_id') 
												GROUP BY gg.STUDENT_ID,gt.ASSIGNMENT_TYPE_ID,gt.FINAL_GRADE_PERCENT"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));
			else
				$points_RET = DBGet(DBQuery("SELECT '-1' AS ASSIGNMENT_TYPE_ID,gg.STUDENT_ID,(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'gg.POINTS')).")) AS PARTIAL_PERCENT_TOP,(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).")) AS PARTIAL_PERCENT_BOTTOM FROM GRADEBOOK_GRADES gg, GRADEBOOK_ASSIGNMENTS ga, SCHEDULE s WHERE gg.COURSE_PERIOD_ID=s.COURSE_PERIOD_ID AND ('".DBDate()."' BETWEEN s.START_DATE AND s.END_DATE OR (s.END_DATE IS NULL AND '".DBDate()."'>=s.START_DATE)) AND ga.ASSIGNMENT_ID=gg.ASSIGNMENT_ID AND ga.MARKING_PERIOD_ID IN (".GetAllMP('QTR',UserMP()).") AND gg.COURSE_PERIOD_ID='$course_period_id' AND (ga.COURSE_PERIOD_ID='$course_period_id' OR ga.COURSE_ID='$course_id') GROUP BY gg.STUDENT_ID"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));
			
			if(count($points_RET))
			{
				foreach($points_RET as $student_id=>$types)
				{
					$total = 0;
					foreach($types as $type_id=>$type)
					{
						if($type[1]['PARTIAL_PERCENT_BOTTOM'])
							$total += ($type[1]['PARTIAL_PERCENT_TOP'] / $type[1]['PARTIAL_PERCENT_BOTTOM']);
					}

					if($programconfig['ROUNDING']=='UP')
						$percent = ceil($total*100);
					elseif($programconfig['ROUNDING']=='DOWN')
						$percent = floor($total*100);
					else
						$percent = round($total*100,0);
	
					if($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['CREDITS']!='Y')
						$carries_credits = '';
					else
						$carries_credits = 'Y';

					if($current_RET[$student_id])
						$sql = "UPDATE STUDENT_REPORT_CARD_GRADES SET GRADE_TITLE='"._makeLetterGrade($total,UserCoursePeriod())."',REPORT_CARD_GRADE_ID='".$grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['ID']."',PERCENT='".$percent."',GPA_POINTS='".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits)."',WEIGHTED_GPA_POINTS='".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits*$gpa_multiplier)."',CREDITS='".$credits."',CARRIES_CREDITS='".$carries_credits."' WHERE STUDENT_ID='".$student_id."' AND COURSE_PERIOD_ID='".$course_period_id."' AND MARKING_PERIOD_ID='".$_REQUEST['mp']."'";
					else
						$sql = "INSERT INTO STUDENT_REPORT_CARD_GRADES (ID,SYEAR,SCHOOL_ID,STUDENT_ID,COURSE_PERIOD_ID,MARKING_PERIOD_ID,REPORT_CARD_GRADE_ID,COURSE_TITLE,TEACHER,GRAD_SUBJECT_ID,LOCATION_TITLE,PERCENT,CREDITS,CARRIES_CREDITS,COURSE_NUM,AFFECTS_GPA,GPA_POINTS,WEIGHTED_GPA_POINTS,GRADE_TITLE,GRADE_SCALE_ID)
								values(".db_seq_nextval('STUDENT_REPORT_CARD_GRADES_SEQ').",'".UserSyear()."','".UserSchool()."','".$student_id."','".$course_period_id."','".$_REQUEST['mp']."','".$grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['ID']."',
										'".$course_title."','".GetTeacher(User('STAFF_ID'))."','".$grad_subject."','".str_replace("'","''",GetSchool(UserSchool()))."','".$percent."','".$credits."','".$carries_credits."','".$course_num."','".$affects_gpa."','".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits)."','".($grades_RET[_makeLetterGrade($total,UserCoursePeriod())][1]['GPA_VALUE']*$credits*$gpa_multiplier)."','"._makeLetterGrade($total,UserCoursePeriod())."','".$grade_scale_id."')";
					DBQuery($sql);
				}
			}
		}
		DBQuery("DELETE FROM GRADES_COMPLETED WHERE STAFF_ID='".User('STAFF_ID')."' AND MARKING_PERIOD_ID='".$_REQUEST['mp']."' AND PERIOD_ID='".UserPeriod()."'");
		DBQuery("INSERT INTO GRADES_COMPLETED (STAFF_ID,MARKING_PERIOD_ID,PERIOD_ID) values('".User('STAFF_ID')."','".$_REQUEST['mp']."','".UserPeriod()."')");

		$current_RET = DBGet(DBQuery("SELECT g.STUDENT_ID,g.REPORT_CARD_GRADE_ID,g.REPORT_CARD_COMMENT_ID,g.COMMENT,g.PERCENT FROM STUDENT_REPORT_CARD_GRADES g,COURSE_PERIODS cp WHERE cp.COURSE_PERIOD_ID=g.COURSE_PERIOD_ID AND cp.COURSE_PERIOD_ID='$course_period_id' AND g.MARKING_PERIOD_ID='".$_REQUEST['mp']."'"),array(),array('STUDENT_ID'));
		unset($_SESSION['_REQUEST_vars']['modfunc']);
		unset($_REQUEST['modfunc']);
	}
}

if($_REQUEST['values'] && $_POST['values'])
{
	$grade_titles_RET = DBGet(DBQuery("SELECT ID,TITLE,GPA_VALUE,CREDITS FROM REPORT_CARD_GRADES WHERE SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."' AND SCALE_ID='".$grade_scale_id."'"),array(),array('ID'));
	$completed = true;
	foreach($_REQUEST['values'] as $student_id=>$columns)
	{
		if($grade_titles_RET[$columns['grade']][1]['CREDITS']!='Y')
			$carries_credits = '';
		else
			$carries_credits = 'Y';

		$sql = '';
		if($current_RET[$student_id])
			$sql = "UPDATE STUDENT_REPORT_CARD_GRADES SET REPORT_CARD_GRADE_ID='".$columns['grade']."',GRADE_TITLE='".$grade_titles_RET[$columns['grade']][1]['TITLE']."', COMMENT='".str_replace("\'","''",$columns['comment'])."',PERCENT='".$columns['percent']."',GPA_POINTS='".($grade_titles_RET[$columns['grade']][1]['GPA_VALUE']*$credits)."',WEIGHTED_GPA_POINTS='".($grade_titles_RET[$columns['grade']][1]['GPA_VALUE']*$credits*$gpa_multiplier)."',CREDITS='".$credits."',CARRIES_CREDITS='".$carries_credits."' WHERE STUDENT_ID='".$student_id."' AND COURSE_PERIOD_ID='".$course_period_id."' AND MARKING_PERIOD_ID='".$_REQUEST['mp']."'";
		elseif($columns['grade'] || $columns['comment'] || $columns['percent'])
			$sql = "INSERT INTO STUDENT_REPORT_CARD_GRADES (ID,SYEAR,SCHOOL_ID,STUDENT_ID,COURSE_PERIOD_ID,MARKING_PERIOD_ID,REPORT_CARD_GRADE_ID,COMMENT,PERCENT,COURSE_TITLE,TEACHER,LOCATION_TITLE,CREDITS,CARRIES_CREDITS,COURSE_NUM,AFFECTS_GPA,GPA_POINTS,WEIGHTED_GPA_POINTS,GRADE_TITLE,GRAD_SUBJECT_ID,GRADE_SCALE_ID)
				values(".db_seq_nextval('STUDENT_REPORT_CARD_GRADES_SEQ').",'".UserSyear()."','".UserSchool()."','".$student_id."','".$course_period_id."','".$_REQUEST['mp']."','".$columns['grade']."','".$columns['comment']."','".$columns['percent']."','".$course_title."','".str_replace("'","''",GetTeacher(User('STAFF_ID')))."','".str_replace("'","''",GetSchool(UserSchool()))."','".$credits."','".$carries_credits."','".$course_num."','".$affects_gpa."','".($grade_titles_RET[$columns['grade']][1]['GPA_VALUE']*$credits)."','".($grade_titles_RET[$columns['grade']][1]['GPA_VALUE']*$credits*$gpa_multiplier)."','".$grade_titles_RET[$columns['grade']][1]['TITLE']."','".$grad_subject."','".$grade_scale_id."')";
		if(!$columns['grade'] && !$columns['comment'])
			$completed = false;
		
		if($sql)
			DBQuery($sql);
	}
	DBQuery("DELETE FROM GRADES_COMPLETED WHERE STAFF_ID='".User('STAFF_ID')."' AND MARKING_PERIOD_ID='".$_REQUEST['mp']."' AND PERIOD_ID='".UserPeriod()."'");
	if($completed)
		DBQuery("INSERT INTO GRADES_COMPLETED (STAFF_ID,MARKING_PERIOD_ID,PERIOD_ID) values('".User('STAFF_ID')."','".$_REQUEST['mp']."','".UserPeriod()."')");

	$current_RET = DBGet(DBQuery("SELECT g.STUDENT_ID,g.REPORT_CARD_GRADE_ID,g.REPORT_CARD_COMMENT_ID,g.COMMENT,g.PERCENT FROM STUDENT_REPORT_CARD_GRADES g,COURSE_PERIODS cp WHERE cp.COURSE_PERIOD_ID=g.COURSE_PERIOD_ID AND cp.COURSE_PERIOD_ID='$course_period_id' AND g.MARKING_PERIOD_ID='".$_REQUEST['mp']."'"),array(),array('STUDENT_ID'));
	unset($_SESSION['_REQUEST_vars']['values']);
}
$extra['SELECT'] = ",'' AS REPORT_CARD_GRADE,'' AS COMMENTS";
$extra['functions'] = array('REPORT_CARD_GRADE'=>'_makeGrade','COMMENTS'=>'_makeComments');

if($_REQUEST['modfunc']!='gradebook')
{
	$fy = GetParentMP('FY',GetParentMP('SEM',UserMP()));
	$sem = GetParentMP('SEM',UserMP());
	$pro = GetChildrenMP('PRO',UserMP());
	$pros = explode(',',str_replace("'",'',$pro));
	$pro_grading = false;
	$pro_select = '';
	$time = strtotime(DBDate('postgres'));
	foreach($pros as $pro)
	{
		if(GetMP($pro,'POST_START_DATE') && ($time >= strtotime(GetMP($pro,'POST_START_DATE')) && $time <= strtotime(GetMP($pro,'POST_END_DATE'))))
		{
			if(!$_REQUEST['mp'])
			{
				$_REQUEST['mp'] = $pro;
				$current_RET = DBGet(DBQuery("SELECT g.STUDENT_ID,g.REPORT_CARD_GRADE_ID,g.REPORT_CARD_COMMENT_ID,g.COMMENT,g.PERCENT FROM STUDENT_REPORT_CARD_GRADES g,COURSE_PERIODS cp WHERE cp.COURSE_PERIOD_ID=g.COURSE_PERIOD_ID AND cp.COURSE_PERIOD_ID='$course_period_id' AND g.MARKING_PERIOD_ID='".$_REQUEST['mp']."'"),array(),array('STUDENT_ID'));
			}
			$pro_grading = true;
			$pro_select .= "<OPTION value=".$pro.(($pro==$_REQUEST['mp'])?' SELECTED':'').">".GetMP($pro)."</OPTION>";
		}
	}
	
	$stu_RET = GetStuList($extra);
	
	if(!$_FOCUS['_makeLetterGrade']['grades'])
		$_FOCUS['_makeLetterGrade']['grades'] = DBGet(DBQuery("SELECT TITLE,ID FROM REPORT_CARD_GRADES WHERE SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."' ORDER BY SORT_ORDER"));
	
	echo '<script language=javascript>
	function makeGrade(percent)
	{
		grade_values = new Array;
		grade_titles = new Array;
	';
	$i = 0;
	foreach($_FOCUS['_makeLetterGrade']['grades'] as $grade)
	{
		if(is_numeric($programconfig[$course_period_id.'-'.$grade['ID']]))
		{
			echo "grade_values[".$i."] = ".$programconfig[$course_period_id.'-'.$grade['ID']].";";
			echo "grade_titles[".$i."] = ".$grade['ID'].";";
			$i++;
		}
	}
	echo '
		for(i=0;i<grade_values.length;i++)
		{
			if(percent>=grade_values[i])
				return grade_titles[i];
		}
	}
	</script>';
	
	
	echo "<FORM action=Modules.php?modname=$_REQUEST[modname] method=POST>";
	
	$mps_select = "<SELECT name=mp onChange='this.form.submit();'>";
	if(!GetMP(UserMP(),'POST_START_DATE') && !GetMP($sem,'POST_START_DATE') && !$pro_grading)
		DrawHeader(ErrorMessage(array(_('There are no available grade posting periods.')),'fatal'),' &nbsp;');
	
	$avail = false;
	
	if(GetMP(UserMP(),'POST_START_DATE') && ($time >= strtotime(GetMP(UserMP(),'POST_START_DATE')) && $time <= strtotime(GetMP(UserMP(),'POST_END_DATE'))))
	{
		$mps_select .= "<OPTION value=".UserMP().">".GetMP(UserMP())."</OPTION>";
		$avail = true;
	}
	elseif($_REQUEST['mp']==UserMP())
		$_REQUEST['mp'] = $sem;
	
	if(GetMP($sem,'POST_START_DATE') && ($time >= strtotime(GetMP($sem,'POST_START_DATE')) && $time <= strtotime(GetMP($sem,'POST_END_DATE'))))
	{
		$mps_select .= "<OPTION value=".$sem.(($sem==$_REQUEST['mp'])?' SELECTED':'').">".GetMP($sem)."</OPTION><OPTION value=E".$sem.(('E'.$sem==$_REQUEST['mp'])?' SELECTED':'').">".GetMP($sem).' '._('Exam').'</OPTION>';
		$avail = true;
	}
	elseif($_REQUEST['mp']==$sem)
		$_REQUEST['mp'] = $fy;
	
	if($pro_grading)
	{
		$mps_select .= $pro_select;
		$avail = true;
	}
	
	if(GetMP($fy,'POST_START_DATE') && ($time >= strtotime(GetMP($fy,'POST_START_DATE')) && $time <= strtotime(GetMP($fy,'POST_END_DATE'))))
	{
		$mps_select .= "<OPTION value=".$fy.(($fy==$_REQUEST['mp'])?' SELECTED':'').">".GetMP($fy).'</OPTION>';
		$avail = true;
	}
	elseif($_REQUEST['mp']==$fy)
		unset($_REQUEST['mp']);
	
	$mps_select .= '</SELECT>';
	
	//if($time < strtotime(GetMP($_REQUEST['mp'],'POST_START_DATE')) || $time > strtotime(GetMP($_REQUEST['mp'],'POST_END_DATE')))
	if(!$avail)
		DrawHeader(ErrorMessage(array(_('There are no available grade posting periods.')),'fatal'),' &nbsp;');
	
	if(!$_REQUEST['_FOCUS_PDF'])
	{
		foreach($comments_RET as $comment)
			$tipmessage .= $comment['TITLE'].'<BR>';
		$tipmessage = button('comment',_('Comment Codes'),'# onClick=\'stm(["'._('Report Card Comments').'","'.$tipmessage.'"],["white","#333366","","","",,"black","#e8e8ff","","","",,,,2,"#333366",2,,,,,"",5,3,50,50]);\'','');
		DrawHeader($mps_select,$tipmessage);
		
		echo '</FORM><FORM ACTION=Modules.php?modname='.$_REQUEST['modname'].'&mp='.$_REQUEST['mp'].' method=POST>';
		if(substr($_REQUEST['mp'],0,1)!='E')
			$gb_header = "<A HREF=Modules.php?modname=$_REQUEST[modname]&modfunc=gradebook&mp=$_REQUEST[mp]>"._('Use Gradebook Grades')."</A>";
		DrawHeader($gb_header,'<INPUT type=submit value='._('Save').'>');
	}
	else
	{
		DrawHeader($cp_title);
		DrawHeader(GetMP(UserMP()));
	}
	
	if(SystemPreferences('REPORT_CARD')=='both')
		$rc_grade_title = _('Percent & Grade');
	elseif(SystemPreferences('REPORT_CARD')=='percent')
		$rc_grade_title = _('Percent');
	elseif(SystemPreferences('REPORT_CARD')=='grade')
		$rc_grade_title = _('Grade');

	$columns = array('FULL_NAME'=>_('Student'),'STUDENT_ID'=>_('Student ID'),'GRADE_ID'=>_('Grade Level'),'REPORT_CARD_GRADE'=>$rc_grade_title,'COMMENTS'=>_('Comments'));
	ListOutput($stu_RET,$columns,_('Student'),_('Students'));
	echo '<CENTER><INPUT type=submit value='._('Save').'></CENTER>';
	echo "</FORM>";
}

function _makeGrade($value,$column)
{	global $THIS_RET,$grades_RET,$current_RET,$tabindex,$_FOCUS;

	if(!isset($_REQUEST['_FOCUS_PDF']))
	{
		$tabindex++;
		if(SystemPreferences('REPORT_CARD')=='both' || SystemPreferences('REPORT_CARD')=='percent')
			$return = "<!-- ".$current_RET[$THIS_RET['STUDENT_ID']][1]['PERCENT']." --><INPUT type=text name=values[$THIS_RET[STUDENT_ID]][percent] value='".$current_RET[$THIS_RET['STUDENT_ID']][1]['PERCENT']."' tabindex=".$tabindex." size=3 onchange='document.getElementById(\"gc$THIS_RET[STUDENT_ID]_\"+makeGrade(this.value)).selected=true;'>% ";
		if(SystemPreferences('REPORT_CARD')=='both' || SystemPreferences('REPORT_CARD')=='grade')
		{
			$return .= "<SELECT name=values[$THIS_RET[STUDENT_ID]][grade]><OPTION value=''></OPTION>";
			foreach($grades_RET as $title=>$code)
			{
				$code = $code[1];
				$return .= "<OPTION id=gc$THIS_RET[STUDENT_ID]_$code[ID] value=$code[ID]".(($current_RET[$THIS_RET['STUDENT_ID']][1]['REPORT_CARD_GRADE_ID']==$code['ID'])?' SELECTED':'').">$code[TITLE]</OPTION>";
			}
			$return .= "</SELECT>";
		}
	}
	else
	{
		$return = '';
		if(SystemPreferences('REPORT_CARD')=='both' || SystemPreferences('REPORT_CARD')=='percent')
			$return = $current_RET[$THIS_RET['STUDENT_ID']][1]['PERCENT'].'%';
		if(SystemPreferences('REPORT_CARD')=='both' || SystemPreferences('REPORT_CARD')=='grade')
		{
			foreach($grades_RET as $title=>$code)
			{
				$code = $code[1];
				$return .= (($current_RET[$THIS_RET['STUDENT_ID']][1]['REPORT_CARD_GRADE_ID']==$code['ID'])?$code['TITLE']:'');
			}
		}
	}
	
	return $return;
}

function _makeComments($value,$column)
{	global $THIS_RET,$comments_RET,$current_RET;

	if(!isset($_REQUEST['_FOCUS_PDF']))
		$return = "<INPUT type=text name=values[$THIS_RET[STUDENT_ID]][comment] value=\"".str_replace('"','\"',$current_RET[$THIS_RET['STUDENT_ID']][1]['COMMENT'])."\">";
	else
		$return = $current_RET[$THIS_RET['STUDENT_ID']][1]['COMMENT'];
		
	/*
	$return .= "<OPTION value=''></OPTION>";
	$return = "<SELECT name=values[$THIS_RET[STUDENT_ID]][comment]><OPTION value=''></OPTION>";
	foreach($comments_RET as $code)
		$return .= "<OPTION value=$code[ID]".(($current_RET[$THIS_RET['STUDENT_ID']][1]['REPORT_CARD_COMMENT_ID']==$code['ID'])?' SELECTED':'').">$code[TITLE]</OPTION>";
	$return .= "</SELECT>";
	*/
	return $return;
}

?>
